package com.bwie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.LoanMapper;
import com.bwie.pojo.EsLoan;
import com.bwie.pojo.Loan;
import com.bwie.service.LoanService;
import com.bwie.util.R;
import com.bwie.vo.LoanVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author 国兴越
 * @version 1.0
 * Create by
 */
@Service
public class LoanServiceImpl extends ServiceImpl<LoanMapper, Loan> implements LoanService {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    LoanMapper loanMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;



    @Override
    public R lists(LoanVo loanVo) {





        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();


        Claims body = Jwts.parser().setSigningKey("bwie").parseClaimsJws(loanVo.getToken()).getBody();

        Integer role = (Integer) body.get("role");

        if(role==1 &&role!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("role",role));
        }
        if(role==2 &&role!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("role",role));
        }
        if(role==3 &&role!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("role",role));
        }
        if(role==4 &&role!=null){
            boolQueryBuilder.must(QueryBuilders.termQuery("role",role));
        }


        if(StringUtils.isNotEmpty(loanVo.getName())){

            boolQueryBuilder.must(QueryBuilders.termQuery("name",loanVo.getName()));

        }
        if(StringUtils.isNotEmpty(loanVo.getStartDate())){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("date").gte(loanVo.getStartDate()));
        }

        if(StringUtils.isNotEmpty(loanVo.getEndDate())){
            boolQueryBuilder.must(QueryBuilders.rangeQuery("date").lte(loanVo.getEndDate()));
        }


        PageRequest pageRequest = PageRequest.of(loanVo.getPageNum() - 1, loanVo.getPageSize());

        HighlightBuilder.Field name = new HighlightBuilder.Field("name").preTags("<font color='red'>").postTags("</font>").requireFieldMatch(false);


        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withPageable(pageRequest)
                .withHighlightFields(name)
                .build();


        SearchHits<EsLoan> search = elasticsearchRestTemplate.search(nativeSearchQuery, EsLoan.class);


        ArrayList<EsLoan> list = new ArrayList<>();

        long total = search.getTotalHits();


        search.forEach(item->{

            EsLoan content = item.getContent();

            List<String> highName = item.getHighlightField("name");

            if(ObjectUtil.isNotEmpty(highName)&& highName.size()>0){

                String s = highName.get(0);
                content.setName(s);

            }
            list.add(content);
        });

        HashMap<String, Object> map = new HashMap<>();
        map.put("total",total);
        map.put("pageNum",loanVo.getPageNum());
        map.put("pageSize",loanVo.getPageSize());

        map.put("list",list);

        return R.ok().message("列表查询成功").data("page",map);
    }




    @Scheduled(cron = "0 0/1 * * * ?")
    public void loan(){

        List<EsLoan> list =loanMapper.lists();
        list.forEach(item->{
            elasticsearchRestTemplate.save(item);
        });

    }


    @Override
    public R add(LoanVo loanVo) {

        Loan loan = BeanUtil.toBean(loanVo, Loan.class);

        Integer role = Integer.valueOf(stringRedisTemplate.opsForValue().get("role"));
        if(role==1){
            loanMapper.insert(loan);
            List<EsLoan> list =loanMapper.lists();
            list.forEach(item->{
                elasticsearchRestTemplate.save(item);
            });
        }
        if(role==2){
            loanMapper.insert(loan);
            List<EsLoan> list =loanMapper.lists();
            list.forEach(item->{
                elasticsearchRestTemplate.save(item);
            });
        }

        return R.ok().message("添加成功");
    }

    @Override
    public R selectById(Integer id) {
        Loan loan=loanMapper.selectById(id);
        Integer role = Integer.valueOf(stringRedisTemplate.opsForValue().get("role"));
        if(role==3){
            loan.setRole(4);
        }
        if(role==4){
            loan.setRole(2);
        }
        loan.setStatus(2);
        loanMapper.updateById(loan);
        List<EsLoan> list =loanMapper.lists();
        list.forEach(item->{
            elasticsearchRestTemplate.save(item);
        });
        return R.ok().message("审批成功");
    }
}
